<template>
  <div class="common-layout">
    <TopNavBar />
    <el-container>
      <el-container>
        <el-main class="chat-main">
          <!-- 聊天标题区域 -->
          <div v-if="messages.length === 0" class="chat-header">
            <h1 class="brand-title">任何情绪！</h1>
            <div class="logo-text">探索无限可能，薇启与你智慧同行</div>
          </div>

          <!-- 聊天内容区域 -->
          <div class="chat-container">
            <div class="chat-history" ref="chatHistory">
              <!-- 欢迎消息 -->
              <div v-if="messages.length === 0" class="welcome-message">
                <div class="welcome-card">
                  <div class="welcome-icon">
                    <img
                      src="@/assets/emo_welcome.png"
                      alt="AI助手"
                      class="welcome-icon-image"
                    />
                  </div>
                  <h3>你好呀，我是你的vichi树洞</h3>
                  <p>我可以帮你解答各种问题，让我们开始对话吧！</p>
                </div>
              </div>

              <!-- 消息列表 -->
              <div
                v-for="(msg, index) in messages"
                :key="index"
                class="message-item"
              >
                <div v-if="msg.role === 'user'" class="user-message">
                  <div class="message-content">
                    <!-- 图片附件 -->
                    <div
                      v-if="msg.attachments && msg.attachments.length > 0"
                      class="message-attachments"
                    >
                      <div
                        v-for="attachment in msg.attachments"
                        :key="attachment.id"
                        class="attachment-item"
                      >
                        <img
                          v-if="attachment.type === 'image'"
                          :src="attachment.base64"
                          :alt="attachment.name"
                          class="attached-image"
                          @click="previewImage(attachment)"
                        />
                        <div
                          v-else-if="attachment.type === 'file'"
                          class="attached-file"
                          @click="downloadFile(attachment)"
                        >
                          <el-icon class="file-icon"><Document /></el-icon>
                          <span class="file-name">{{ attachment.name }}</span>
                          <span class="file-size">{{
                            formatFileSize(attachment.size)
                          }}</span>
                        </div>
                      </div>
                    </div>
                    <!-- 文本内容 -->
                    <div
                      v-if="msg.content"
                      class="message-text"
                      ref="userMessageText"
                    >
                      {{ msg.content }}
                    </div>
                  </div>
                  <div class="message-avatar">
                    <el-avatar :size="36" class="user-avatar">
                      <el-icon><User /></el-icon>
                    </el-avatar>
                  </div>
                </div>
                <div v-else class="assistant-message">
                  <div class="message-avatar">
                    <el-avatar :size="36" class="ai-avatar">
                      <el-icon><ChatRound /></el-icon>
                    </el-avatar>
                  </div>
                  <div class="message-content">
                    <div class="message-text" ref="assistantMessageText">
                      {{ msg.content }}
                    </div>
                  </div>
                </div>
              </div>

              <!-- 流式消息 -->
              <div v-if="streamingContent" class="streaming-message">
                <div class="message-avatar">
                  <el-avatar :size="36" class="ai-avatar streaming">
                    <el-icon><ChatRound /></el-icon>
                  </el-avatar>
                </div>
                <div class="message-content">
                  <div
                    class="message-text typing-animation"
                    ref="streamingText"
                  >
                    {{ streamingContent }}
                    <span class="typing-cursor">|</span>
                  </div>
                </div>
              </div>
            </div>

            <!-- 推荐追问 -->
            <div
              v-if="followUpQuestions.length > 0"
              class="follow-up-container"
            >
              <div class="follow-up-title">
                <el-icon><QuestionFilled /></el-icon>
                推荐追问
              </div>
              <div class="follow-up-questions">
                <el-button
                  v-for="(question, idx) in followUpQuestions"
                  :key="idx"
                  class="follow-up-btn"
                  @click="sendFollowUp(question)"
                >
                  {{ question }}
                </el-button>
              </div>
            </div>

            <!-- 输入区域 -->
            <div
              class="chat-input-container"
              :class="{ 'drag-over': isDragOver }"
              @dragover="handleDragOver"
              @dragleave="handleDragLeave"
              @drop="handleDrop"
            >
              <!-- 附件预览区域 -->
              <div v-if="attachments.length > 0" class="attachments-preview">
                <div class="attachments-header">
                  <span class="attachments-title">{{
                    getAttachmentSummary()
                  }}</span>
                  <el-button
                    size="small"
                    text
                    @click="attachments = []"
                    :disabled="isLoading"
                  >
                    清空
                  </el-button>
                </div>
                <div class="attachments-grid">
                  <div
                    v-for="attachment in attachments"
                    :key="attachment.id"
                    class="attachment-preview"
                  >
                    <img
                      v-if="attachment.type === 'image'"
                      :src="attachment.thumbnail"
                      :alt="attachment.name"
                    />
                    <el-icon
                      v-else-if="attachment.type === 'file'"
                      class="file-preview-icon"
                      size="32"
                    >
                      <Document />
                    </el-icon>
                    <div class="attachment-info">
                      <span class="attachment-name">{{ attachment.name }}</span>
                      <span class="attachment-size">{{
                        formatFileSize(attachment.size)
                      }}</span>
                    </div>
                    <el-button
                      class="remove-btn"
                      :icon="Close"
                      size="small"
                      circle
                      @click="removeAttachment(attachment.id)"
                      :disabled="isLoading"
                    />
                  </div>
                </div>
              </div>

              <!-- 上传进度 -->
              <div v-if="isUploading" class="upload-progress">
                <el-progress :percentage="uploadProgress" :show-text="false" />
                <span class="progress-text"
                  >处理图片中... {{ Math.round(uploadProgress) }}%</span
                >
              </div>

              <!-- 拖拽提示 -->
              <div v-if="isDragOver" class="drag-overlay">
                <div class="drag-content">
                  <el-icon size="48" color="#409eff"><Upload /></el-icon>
                  <p>释放鼠标上传文件</p>
                </div>
              </div>

              <div class="input-wrapper">
                <div class="input-container">
                  <el-input
                    v-model="userInput"
                    placeholder="输入你的问题，与AI开始对话...(Ctrl+Enter发送消息，Enter换行)"
                    :rows="1"
                    type="textarea"
                    class="chat-input"
                    autosize
                    @keyup.enter.native="handleEnterKey"
                    :disabled="isLoading"
                  />
                  <div class="input-actions">
                    <!-- 图片上传按钮 -->
                    <el-tooltip content="上传图片" placement="top">
                      <el-button
                        :icon="Picture"
                        circle
                        size="small"
                        @click="selectImages"
                        :disabled="isLoading || isUploading"
                        class="upload-btn"
                      />
                    </el-tooltip>
                    <!-- 文件上传按钮 -->
                    <el-tooltip content="上传文件" placement="top">
                      <el-button
                        :icon="Document"
                        circle
                        size="small"
                        @click="selectFiles"
                        :disabled="isLoading || isUploading"
                        class="upload-btn"
                      />
                    </el-tooltip>
                    <!-- 发送按钮 -->
                    <el-tooltip content="发送消息 (Ctrl+Enter)" placement="top">
                      <el-button
                        type="primary"
                        :icon="Position"
                        circle
                        size="small"
                        @click="sendMessage"
                        :loading="isLoading"
                        :disabled="
                          (!userInput.trim() && attachments.length === 0) ||
                          isLoading
                        "
                        class="send-btn"
                      />
                    </el-tooltip>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from "vue";
import { ElMessage } from "element-plus";
import TopNavBar from "@/components/TopNavBar.vue";
import {
  User,
  ChatRound,
  QuestionFilled,
  Position,
  Picture,
  Close,
  Upload,
  Document,
} from "@element-plus/icons-vue";
import katex from "katex";
import "katex/dist/katex.min.css";
import requestUtil from "@/util/request";

// 组件状态
const messages = ref([]);
const userInput = ref("");
const streamingContent = ref("");
const followUpQuestions = ref([]);
const isLoading = ref(false);
const conversationId = ref("");
const currentAssistantMessage = ref(null);
const chatHistory = ref(null);

// 用户信息
const userInfo = ref(null);

// 图片上传相关状态
const attachments = ref([]);
const isDragOver = ref(false);
const uploadProgress = ref(0);
const isUploading = ref(false);

// API配置
const API_URL = "https://api.coze.cn/v3/chat";
const API_KEY =
  "pat_NOrsA24YEKmGN6peXeP1rT37hUFyvaEuaM18QYsHZzwFpUkkXSUV4G7P3440i7Cj";
const BOT_ID = "7517556753664622607";

// 存储相关配置
const MAX_HISTORY_MESSAGES = 1000;

// 基于用户ID的存储key生成
const getChatStorageKey = (userId) => `vichi_emotion_chat_${userId}`;
const getHistoryStorageKey = (userId) => `vichi_emotion_history_${userId}`;

// 保存当前聊天记录到localStorage
const saveCurrentChat = () => {
  try {
    const userId = getUserId();
    const dataToStore = {
      messages: messages.value,
      conversationId: conversationId.value,
      timestamp: Date.now(),
    };
    localStorage.setItem(
      getChatStorageKey(userId),
      JSON.stringify(dataToStore)
    );
  } catch (error) {
    console.warn("保存当前对话失败:", error);
  }
};

// 加载当前聊天记录从localStorage
const loadCurrentChat = () => {
  try {
    const userId = getUserId();
    const stored = localStorage.getItem(getChatStorageKey(userId));
    if (stored) {
      const data = JSON.parse(stored);
      if (data.messages && Array.isArray(data.messages)) {
        messages.value = data.messages;
        conversationId.value = data.conversationId || "";
        return true;
      }
    }
  } catch (error) {
    console.warn("加载当前对话失败:", error);
  }
  return false;
};

// 保存消息到历史记录
const saveToHistory = (message) => {
  try {
    const userId = getUserId();
    const historyKey = getHistoryStorageKey(userId);
    const stored = localStorage.getItem(historyKey);
    let historyData = { messages: [], timestamp: Date.now() };

    if (stored) {
      historyData = JSON.parse(stored);
      if (!historyData.messages) {
        historyData.messages = [];
      }
    }

    // 添加时间戳和会话ID到消息
    const messageWithMeta = {
      ...message,
      timestamp: Date.now(),
      sessionId: conversationId.value || generateSessionId(),
    };

    historyData.messages.push(messageWithMeta);

    // 保持历史记录在限制范围内
    if (historyData.messages.length > MAX_HISTORY_MESSAGES) {
      historyData.messages = historyData.messages.slice(-MAX_HISTORY_MESSAGES);
    }

    historyData.timestamp = Date.now();
    localStorage.setItem(historyKey, JSON.stringify(historyData));
  } catch (error) {
    console.warn("保存历史记录失败:", error);
  }
};

// 获取用户的聊天历史记录
const getUserChatHistory = () => {
  try {
    const userId = getUserId();
    const historyKey = getHistoryStorageKey(userId);
    const stored = localStorage.getItem(historyKey);
    if (stored) {
      const data = JSON.parse(stored);
      return data.messages || [];
    }
  } catch (error) {
    console.warn("获取聊天历史记录失败:", error);
  }
  return [];
};

// 清除当前用户的聊天记录
const clearCurrentUserChat = () => {
  try {
    const userId = getUserId();
    localStorage.removeItem(getChatStorageKey(userId));
    messages.value = [];
    conversationId.value = "";
    followUpQuestions.value = [];
    streamingContent.value = "";
    currentAssistantMessage.value = null;
  } catch (error) {
    console.warn("清除当前对话失败:", error);
  }
};

// 清除当前用户的历史记录
const clearCurrentUserHistory = () => {
  try {
    const userId = getUserId();
    localStorage.removeItem(getHistoryStorageKey(userId));
  } catch (error) {
    console.warn("清除历史记录失败:", error);
  }
};

// 生成会话ID
const generateSessionId = () => {
  return Date.now().toString(36) + Math.random().toString(36).substr(2);
};

// 图片处理相关配置
const imageConfig = {
  maxSize: 5 * 1024 * 1024, // 5MB
  maxWidth: 1920,
  maxHeight: 1080,
  quality: 0.8,
  supportedTypes: [
    "image/jpeg",
    "image/png",
    "image/gif",
    "image/webp",
    "image/bmp",
  ],
};

// 文件处理相关配置
const fileConfig = {
  maxSize: 10 * 1024 * 1024, // 10MB
  supportedTypes: [
    // 文档类型
    "application/pdf",
    "application/msword",
    "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
    "application/vnd.ms-excel",
    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    "application/vnd.ms-powerpoint",
    "application/vnd.openxmlformats-officedocument.presentationml.presentation",
    // 文本类型
    "text/plain",
    "text/csv",
    "application/json",
    "application/xml",
    "text/xml",
    // 压缩文件
    "application/zip",
    "application/x-rar-compressed",
    "application/x-7z-compressed",
    // 其他常见类型
    "application/rtf",
  ],
};

// 检查文件类型
const isValidImageType = (file) => {
  return imageConfig.supportedTypes.includes(file.type);
};

// 检查文件大小
const isValidImageSize = (file) => {
  return file.size <= imageConfig.maxSize;
};

// 检查是否为支持的文件类型
const isValidFileType = (file) => {
  return fileConfig.supportedTypes.includes(file.type);
};

// 检查文件大小
const isValidFileSize = (file) => {
  return file.size <= fileConfig.maxSize;
};

// 压缩图片
const compressImage = (file, quality = imageConfig.quality) => {
  return new Promise((resolve) => {
    const canvas = document.createElement("canvas");
    const ctx = canvas.getContext("2d");
    const img = new Image();

    img.onload = () => {
      // 计算压缩后的尺寸
      let { width, height } = img;
      const maxWidth = imageConfig.maxWidth;
      const maxHeight = imageConfig.maxHeight;

      if (width > maxWidth || height > maxHeight) {
        const ratio = Math.min(maxWidth / width, maxHeight / height);
        width *= ratio;
        height *= ratio;
      }

      canvas.width = width;
      canvas.height = height;

      // 绘制压缩后的图片
      ctx.drawImage(img, 0, 0, width, height);

      // 转换为blob
      canvas.toBlob(resolve, file.type, quality);
    };

    img.src = URL.createObjectURL(file);
  });
};

// 将文件转换为Base64
const fileToBase64 = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => resolve(reader.result);
    reader.onerror = reject;
    reader.readAsDataURL(file);
  });
};

// 生成缩略图
const generateThumbnail = (file, maxSize = 150) => {
  return new Promise((resolve) => {
    const canvas = document.createElement("canvas");
    const ctx = canvas.getContext("2d");
    const img = new Image();

    img.onload = () => {
      const { width, height } = img;
      const ratio = Math.min(maxSize / width, maxSize / height);
      const newWidth = width * ratio;
      const newHeight = height * ratio;

      canvas.width = newWidth;
      canvas.height = newHeight;

      ctx.drawImage(img, 0, 0, newWidth, newHeight);
      resolve(canvas.toDataURL("image/jpeg", 0.7));
    };

    img.src = URL.createObjectURL(file);
  });
};

// 上传图片到后端服务器
const uploadImageToBackend = async (file) => {
  const formData = new FormData();
  formData.append("file", file); // 与后端接口参数名一致

  try {
    const response = await requestUtil.post(
      "/upload",
      formData, // 直接传递FormData对象
      {
        headers: {
          token: sessionStorage.getItem("token") || "", // 传递token
        },
      }
    );
    console.log("上传响应:", response);

    // 后端返回格式：response.data.data 包含实际的文件信息
    if (response.data.code === 200 && response.data.data?.url) {
      return response.data.data; // 返回嵌套的 data 对象
    } else {
      throw new Error(
        `上传失败: ${response.data.message || "后端未返回有效数据"}`
      );
    }
  } catch (error) {
    console.error("上传图片到后端失败:", error);
    ElMessage.error(`图片上传失败: ${error.message}`);
    throw error; // 抛出错误，让上层处理
  }
};

// 上传文件到后端服务器
const uploadFileToBackend = async (file) => {
  const formData = new FormData();
  formData.append("file", file); // 与后端接口参数名一致

  try {
    const response = await requestUtil.post(
      "/upload",
      formData, // 直接传递FormData对象
      {
        headers: {
          token: sessionStorage.getItem("token") || "", // 传递token
        },
      }
    );
    console.log("文件上传响应:", response);

    // 后端返回格式：response.data.data 包含实际的文件信息
    if (response.data.code === 200 && response.data.data?.url) {
      return response.data.data; // 返回嵌套的 data 对象
    } else {
      throw new Error(
        `上传失败: ${response.data.message || "后端未返回有效数据"}`
      );
    }
  } catch (error) {
    console.error("上传文件到后端失败:", error);
    ElMessage.error(`文件上传失败: ${error.message}`);
    throw error; // 抛出错误，让上层处理
  }
};

// 处理图片上传
const handleImageUpload = async (files) => {
  isUploading.value = true;
  uploadProgress.value = 0;

  try {
    const processedFiles = [];

    for (let i = 0; i < files.length; i++) {
      const file = files[i];

      // 验证文件类型
      if (!isValidImageType(file)) {
        ElMessage.warning(`文件 ${file.name} 不是支持的图片格式`);
        continue;
      }

      // 验证文件大小
      if (!isValidImageSize(file)) {
        ElMessage.warning(`文件 ${file.name} 大小超过限制（5MB）`);
        continue;
      }

      // 压缩图片
      const compressedFile = await compressImage(file);

      // 转换为Base64
      const base64 = await fileToBase64(compressedFile);

      // 生成缩略图
      const thumbnail = await generateThumbnail(file);

      // 创建附件对象
      const attachment = {
        id: Date.now() + i,
        type: "image",
        name: file.name,
        size: compressedFile.size,
        mimeType: file.type,
        base64: base64,
        thumbnail: thumbnail,
        originalSize: file.size,
      };

      processedFiles.push(attachment);
      uploadProgress.value = ((i + 1) / files.length) * 100;
    }

    // 添加到附件列表
    attachments.value.push(...processedFiles);

    if (processedFiles.length > 0) {
      ElMessage.success(`成功添加 ${processedFiles.length} 张图片`);
    }
  } catch (error) {
    console.error("图片处理失败:", error);
    ElMessage.error("图片处理失败，请重试");
  } finally {
    isUploading.value = false;
    uploadProgress.value = 0;
  }
};

// 处理文件上传
const handleFileUpload = async (files) => {
  isUploading.value = true;
  uploadProgress.value = 0;

  try {
    const processedFiles = [];

    for (let i = 0; i < files.length; i++) {
      const file = files[i];

      // 验证文件类型
      if (!isValidFileType(file)) {
        ElMessage.warning(`文件 ${file.name} 不是支持的文件格式`);
        continue;
      }

      // 验证文件大小
      if (!isValidFileSize(file)) {
        ElMessage.warning(`文件 ${file.name} 大小超过限制（10MB）`);
        continue;
      }

      // 转换文件为Base64（用于本地预览）
      const base64 = await fileToBase64(file);

      // 创建附件对象
      const attachment = {
        id: Date.now() + i,
        type: "file",
        name: file.name,
        size: file.size,
        mimeType: file.type,
        base64: base64,
        originalSize: file.size,
      };

      processedFiles.push(attachment);
      uploadProgress.value = ((i + 1) / files.length) * 100;
    }

    // 添加到附件列表
    attachments.value.push(...processedFiles);

    if (processedFiles.length > 0) {
      ElMessage.success(`成功添加 ${processedFiles.length} 个文件`);
    }
  } catch (error) {
    console.error("文件处理失败:", error);
    ElMessage.error("文件处理失败，请重试");
  } finally {
    isUploading.value = false;
    uploadProgress.value = 0;
  }
};

// 选择文件
const selectFiles = () => {
  console.log("selectFiles method called");
  const input = document.createElement("input");
  input.type = "file";
  input.accept = fileConfig.supportedTypes.join(",");
  input.multiple = true;

  input.onchange = (e) => {
    const files = Array.from(e.target.files);
    if (files.length > 0) {
      handleFileUpload(files);
    }
  };

  input.click();
};
const selectImages = () => {
  console.log("selectImages method called");
  const input = document.createElement("input");
  input.type = "file";
  input.accept = "image/*";
  input.multiple = true;

  input.onchange = (e) => {
    const files = Array.from(e.target.files);
    if (files.length > 0) {
      handleImageUpload(files);
    }
  };

  input.click();
};

// 删除附件
const removeAttachment = (id) => {
  attachments.value = attachments.value.filter((item) => item.id !== id);
};

// 拖拽处理
const handleDragOver = (e) => {
  e.preventDefault();
  e.stopPropagation();
  if (!isDragOver.value) {
    isDragOver.value = true;
  }
};

const handleDragLeave = (e) => {
  e.preventDefault();
  e.stopPropagation();
  // 只有当鼠标真正离开拖拽区域时才设置为false
  if (!e.currentTarget.contains(e.relatedTarget)) {
    isDragOver.value = false;
  }
};

const handleDrop = (e) => {
  e.preventDefault();
  e.stopPropagation();
  isDragOver.value = false;

  const droppedFiles = Array.from(e.dataTransfer.files);
  const imageFiles = droppedFiles.filter((file) =>
    file.type.startsWith("image/")
  );
  const otherFiles = droppedFiles.filter(
    (file) => !file.type.startsWith("image/") && isValidFileType(file)
  );

  if (imageFiles.length > 0) {
    handleImageUpload(imageFiles);
  }

  if (otherFiles.length > 0) {
    handleFileUpload(otherFiles);
  }

  const unsupportedFiles = droppedFiles.filter(
    (file) => !file.type.startsWith("image/") && !isValidFileType(file)
  );

  if (unsupportedFiles.length > 0) {
    ElMessage.warning(`${unsupportedFiles.length} 个文件格式不支持`);
  }
};

// 获取附件摘要信息
const getAttachmentSummary = () => {
  const images = attachments.value.filter((att) => att.type === "image").length;
  const files = attachments.value.filter((att) => att.type === "file").length;

  const parts = [];
  if (images > 0) parts.push(`${images} 张图片`);
  if (files > 0) parts.push(`${files} 个文件`);

  return parts.join("，");
};

// 下载文件
const downloadFile = (attachment) => {
  const link = document.createElement("a");
  link.href = attachment.base64;
  link.download = attachment.name;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};
const formatFileSize = (bytes) => {
  if (bytes === 0) return "0 B";
  const k = 1024;
  const sizes = ["B", "KB", "MB", "GB"];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
};

// 图片预览
const previewImage = (attachment) => {
  // 创建预览弹窗
  const overlay = document.createElement("div");
  overlay.className = "image-preview-overlay";
  overlay.innerHTML = `
    <div class="image-preview-container">
      <img src="${attachment.base64}" alt="${
    attachment.name
  }" class="preview-image" />
      <div class="preview-info">
        <h4>${attachment.name}</h4>
        <p>大小: ${formatFileSize(attachment.originalSize)}</p>
      </div>
      <button class="preview-close">&times;</button>
    </div>
  `;

  // 点击关闭
  overlay.addEventListener("click", (e) => {
    if (e.target === overlay || e.target.className === "preview-close") {
      document.body.removeChild(overlay);
    }
  });

  document.body.appendChild(overlay);
};

// 清除当前对话（不影响全局历史）
const clearCurrentChat = () => {
  clearCurrentUserChat();
};

// 处理Enter键
const handleEnterKey = (event) => {
  if (event.ctrlKey || event.metaKey) {
    // Ctrl+Enter 或 Cmd+Enter 发送消息
    sendMessage();
  }
  // 普通Enter键不发送消息，允许换行
};

// 辅助函数：将base64字符串转换为Blob对象
const base64ToBlob = (base64String, mimeType) => {
  // 分割base64字符串（格式通常为 ""）
  const parts = base64String.split(",");
  // 解码base64数据（取逗号后面的部分）
  const decodedData = window.atob(parts[1]);

  // 创建 Uint8Array 存储二进制数据
  const uint8Array = new Uint8Array(decodedData.length);
  for (let i = 0; i < decodedData.length; i++) {
    uint8Array[i] = decodedData.charCodeAt(i);
  }

  // 返回Blob对象（二进制大对象）
  return new Blob([uint8Array], { type: mimeType });
};

// 获取用户信息
const getUserInfo = () => {
  try {
    const userInfoStr = sessionStorage.getItem("userInfo");
    if (userInfoStr) {
      const parsedUserInfo = JSON.parse(userInfoStr);
      console.log("获取到的用户信息:", parsedUserInfo);
      return parsedUserInfo;
    } else {
      console.warn("sessionStorage中未找到userinfo，用户可能未登录");
      return null;
    }
  } catch (error) {
    console.error("解析用户信息失败:", error);
    return null;
  }
};

// 获取用户ID，如果获取失败则使用默认值
const getUserId = () => {
  const userInfoData = getUserInfo();
  if (userInfoData && userInfoData.id) {
    const userId = userInfoData.id.toString();
    console.log("使用用户ID:", userId);
    return userId;
  } else {
    console.warn('无法获取用户ID，使用默认值 "1"');
    return "1"; // 默认值
  }
};

const getUserName = () => {
  const userInfoData = getUserInfo();
  if (userInfoData && userInfoData.username) {
    const username = userInfoData.username;
    console.log("使用用户名:", username);
    return username;
  } else {
    console.warn('无法获取用户名，使用默认值 "用户"');
    return "xv"; // 默认用户名
  }
};

// 发送消息到API
const sendMessage = async () => {
  const content = userInput.value.trim();
  const hasAttachments = attachments.value.length > 0;

  // 检查是否有内容或附件
  if (!content && !hasAttachments) {
    ElMessage.warning("请输入消息内容或上传图片");
    return;
  }

  // 构建用户消息（用于显示）
  const userMessage = {
    role: "user",
    content,
    attachments: hasAttachments ? [...attachments.value] : undefined,
  };

  // 添加到消息列表
  messages.value.push(userMessage);

  // 保存当前聊天记录
  saveCurrentChat();
  // 保存到历史记录
  saveToHistory(userMessage);

  // 清空输入和附件
  const currentAttachments = [...attachments.value]; // 保存当前附件
  userInput.value = "";
  attachments.value = [];
  streamingContent.value = "";
  followUpQuestions.value = [];
  isLoading.value = true;
  currentAssistantMessage.value = null;

  try {
    // 1. 如果有附件，先上传到后端获取URL
    const uploadedUrls = [];
    if (currentAttachments.length > 0) {
      for (const attachment of currentAttachments) {
        try {
          // 将base64转为二进制文件
          const blob = base64ToBlob(attachment.base64, attachment.mimeType);
          const file = new File([blob], attachment.name, {
            type: attachment.mimeType,
          });

          // 根据类型调用不同的上传接口
          let uploadResult;
          if (attachment.type === "image") {
            uploadResult = await uploadImageToBackend(file);
          } else if (attachment.type === "file") {
            uploadResult = await uploadFileToBackend(file);
          }

          uploadedUrls.push({
            url: uploadResult.url,
            type: attachment.type,
            name: attachment.name,
          });
          console.log(`${attachment.type}上传成功:`, uploadResult.url);
        } catch (error) {
          console.error(`上传${attachment.type}失败:`, error);
          ElMessage.error(`${attachment.name} 上传失败`);
          // 继续处理其他文件，不阻止消息发送
        }
      }
    }

    // 2. 构建API消息格式
    const messageContent = [];
    if (content) {
      messageContent.push({ type: "text", text: content });
    }

    // 添加成功上传的文件URL
    uploadedUrls.forEach((item) => {
      if (item.type === "image") {
        messageContent.push({
          type: "image",
          file_url: item.url,
        });
      } else if (item.type === "file") {
        messageContent.push({
          type: "file",
          file_url: item.url,
        });
      }
    });

    console.log("发送的消息内容:", messageContent);

    const requestBody = {
      bot_id: BOT_ID,
      user_id: getUserId(),
      stream: true,
      auto_save_history: true,
      parameters: {
        user: [
          {
            user_id: getUserId(),
            user_name: getUserName(),
          },
        ],
      },
      additional_messages: [
        {
          role: "user",
          content_type:
            messageContent.length > 1 || uploadedUrls.length > 0
              ? "object_string"
              : "text",
          content:
            messageContent.length > 1 || uploadedUrls.length > 0
              ? JSON.stringify(messageContent)
              : content,
        },
      ],
    };

    console.log("完整的请求体:", JSON.stringify(requestBody, null, 2));

    const response = await fetch(API_URL, {
      method: "POST",
      headers: {
        Authorization: `Bearer ${API_KEY}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify(requestBody),
    });

    if (!response.ok) {
      const errorText = await response.text();
      console.error("API响应错误:", {
        status: response.status,
        statusText: response.statusText,
        body: errorText,
      });
      throw new Error(`API请求失败: ${response.status}`);
    }

    await processStream(response.body);
  } catch (error) {
    console.error("发送消息错误:", error);
    ElMessage.error("发送消息失败，请重试");
  } finally {
    isLoading.value = false;
    // 自动滚动到底部
    setTimeout(() => {
      if (chatHistory.value) {
        chatHistory.value.scrollTop = chatHistory.value.scrollHeight;
      }
    }, 100);
  }
};

// 处理流式响应
const processStream = async (body) => {
  const reader = body.getReader();
  const decoder = new TextDecoder();
  let accumulatedData = "";

  try {
    while (true) {
      const { done, value } = await reader.read();

      if (done) {
        console.log("流式响应结束");

        break;
      }

      // 解码数据并累积数据
      const chunk = decoder.decode(value, { stream: true });
      accumulatedData += chunk;

      // 处理JSON数据，处理可能存在的多个JSON块
      let jsonStart = accumulatedData.indexOf("{");
      while (jsonStart !== -1) {
        // 寻找JSON结束符
        let jsonEnd = findJsonEnd(accumulatedData, jsonStart);
        if (jsonEnd === -1) {
          // 没有找到完整的JSON，保留数据继续累积
          break;
        }

        // 提取完整的JSON
        const jsonStr = accumulatedData.substring(jsonStart, jsonEnd + 1);
        processMessage(jsonStr);

        // 继续处理剩余数据
        accumulatedData = accumulatedData.substring(jsonEnd + 1);
        jsonStart = accumulatedData.indexOf("{");
      }
    }
  } catch (error) {
    console.error("流式处理错误:", error);
    ElMessage.error("消息处理失败");
  }
};

// 辅助函数：寻找JSON结束位置
const findJsonEnd = (str, startIndex) => {
  let depth = 0;
  for (let i = startIndex; i < str.length; i++) {
    if (str[i] === "{") depth++;
    else if (str[i] === "}") depth--;
    if (depth === 0) return i;
  }
  return -1;
};

// 解析和处理单个消息
const processMessage = (message) => {
  try {
    // 尝试解析JSON
    let jsonData;
    try {
      jsonData = JSON.parse(message);
    } catch (e) {
      console.warn("不完整的JSON:", message);
      return;
    }

    // 保存对话 ID
    if (jsonData.conversation_id) {
      conversationId.value = jsonData.conversation_id;
    }

    // 处理 assistant 角色的消息
    if (jsonData.role === "assistant") {
      // 初始化当前消息对象
      if (!currentAssistantMessage.value) {
        currentAssistantMessage.value = {
          role: "assistant",
          content: "",
        };
        messages.value.push(currentAssistantMessage.value);
      }

      // 处理流式 delta 内容
      if (jsonData.type === "delta" && jsonData.content) {
        currentAssistantMessage.value.content += jsonData.content;
        streamingContent.value = currentAssistantMessage.value.content;
      }

      // 处理完整回答
      if (jsonData.type === "answer" && jsonData.content) {
        // 如果delta内容存在且与完整内容的开头匹配，则使用完整内容
        if (
          currentAssistantMessage.value.content &&
          jsonData.content.startsWith(currentAssistantMessage.value.content)
        ) {
          // 完整内容包含了所有delta内容，直接使用完整内容
          currentAssistantMessage.value.content = jsonData.content;
        } else if (!currentAssistantMessage.value.content) {
          // 如果没有delta内容，直接使用完整内容
          currentAssistantMessage.value.content = jsonData.content;
        }
        // 如果delta内容存在但不匹配，保持delta内容（可能API行为不一致）

        streamingContent.value = currentAssistantMessage.value.content;
      }

      // 处理追问问题
      if (jsonData.type === "follow_up" && jsonData.content) {
        followUpQuestions.value.push(jsonData.content);
      }

      // 对话完成时清理
      if (
        jsonData.type === "answer" ||
        message.includes("conversation.chat.completed")
      ) {
        streamingContent.value = "";

        // 当回答完成后，触发公式渲染
        nextTick(() => {
          if (currentAssistantMessage.value) {
            renderLatex();
            // 保存助手消息到历史记录
            saveToHistory(currentAssistantMessage.value);
            // 保存当前聊天记录
            saveCurrentChat();
          }
        });
      }
    }
  } catch (error) {
    console.warn("消息解析失败:", message, error);
  }
};

// 发送推荐追问
const sendFollowUp = (question) => {
  userInput.value = question;
  sendMessage();
};

// 渲染LaTeX公式的函数
const renderLatex = () => {
  // 获取所有消息文本元素
  const messageElements = document.querySelectorAll(".message-text");
  messageElements.forEach((el) => {
    // 克隆原始节点以避免修改原始 DOM
    const tempDiv = document.createElement("div");
    tempDiv.innerHTML = el.innerHTML;

    // 查找所有块级公式（$$...$$）
    const blockFormulas = tempDiv.innerHTML.match(/\$\$(.*?)\$\$/g) || [];
    blockFormulas.forEach((formula) => {
      const formulaContent = formula.slice(2, -2); // 去掉$$
      try {
        const katexDiv = document.createElement("div");
        katex.render(formulaContent, katexDiv, {
          displayMode: true,
          throwOnError: false,
          trust: true,
        });
        el.innerHTML = el.innerHTML.replace(formula, katexDiv.innerHTML);
      } catch (error) {
        console.error("KaTeX渲染错误:", error);
        el.innerHTML = el.innerHTML.replace(
          formula,
          `<span class="katex-error">$$${formulaContent}$$</span>`
        );
      }
    });

    // 查找所有行内公式（$...$）
    const inlineFormulas = tempDiv.innerHTML.match(/\$(.*?)\$/g) || [];
    inlineFormulas.forEach((formula) => {
      const formulaContent = formula.slice(1, -1); // 去掉$
      try {
        const katexSpan = document.createElement("span");
        katex.render(formulaContent, katexSpan, {
          displayMode: false,
          throwOnError: false,
          trust: true,
        });
        el.innerHTML = el.innerHTML.replace(formula, katexSpan.innerHTML);
      } catch (error) {
        console.error("KaTeX渲染错误:", error);
        el.innerHTML = el.innerHTML.replace(
          formula,
          `<span class="katex-error">${formula}</span>`
        );
      }
    });
  });
};

// 初始化
onMounted(() => {
  // 初始化用户信息
  userInfo.value = getUserInfo();
  if (userInfo.value) {
    console.log("用户登录状态正常，用户ID:", userInfo.value.id);
    // 加载当前用户的聊天记录
    const restored = loadCurrentChat();
    if (restored) {
      console.log("成功恢复情绪聊天记录，消息数量:", messages.value.length);
    } else {
      console.log("未找到情绪聊天记录，开始新的对话");
    }
  } else {
    console.warn("用户未登录或用户信息不完整");
  }
});
</script>

<style scoped>
/* 全局布局 */
html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

.common-layout {
  height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.el-container {
  height: 100%;
}

.chat-main {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 0;
  background: transparent;
}

/* 聊天标题区域 */
.chat-header {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 40px 20px 20px;
  background: transparent;
}

.brand-title {
  font-size: 3.5rem;
  color: #222;
  font-weight: 900;
  margin-bottom: 8px;
  text-shadow: 2px 2px 0 #fff, 4px 4px 0 rgba(0, 0, 0, 0.1);
  background: linear-gradient(45deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.logo-text {
  font-size: 16px;
  color: #666;
  font-weight: 400;
  opacity: 0.8;
}

/* 聊天容器 */
.chat-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  /* max-width: 900px; */
  width: 100%;
  margin: 0 auto;
  padding: 0 20px;
  min-height: 0;
}

/* 聊天历史区域 */
.chat-history {
  flex: 1;
  overflow-y: auto;
  padding: 20px 0;
  /* 隐藏滚动条但保持滚动功能 */
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE 和 Edge */
}

/* 隐藏 WebKit 浏览器的滚动条 */
.chat-history::-webkit-scrollbar {
  display: none;
}

/* 欢迎消息 */
.welcome-message {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
}

.welcome-card {
  text-align: center;
  padding: 40px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 20px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  max-width: 400px;
}

/* 欢迎消息图标样式 */
.welcome-icon {
  font-size: 3rem;
  display: flex;
  justify-content: center;
  align-items: center;
}

.welcome-icon-image {
  width: 100px;
  height: 100px;
  object-fit: contain;
  border-radius: 12px;
  transition: transform 0.3s ease;
}

.welcome-card h3 {
  color: #333;
  font-size: 1.5rem;
  margin-bottom: 10px;
  font-weight: 600;
}

.welcome-card p {
  color: #666;
  font-size: 1rem;
  line-height: 1.6;
  margin: 0;
}

/* 消息项 */
.message-item {
  margin-bottom: 24px;
  display: flex;
  align-items: flex-start;
  animation: fadeInUp 0.3s ease-out;
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 用户消息 */
.user-message {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  width: 100%;
}

.user-message .message-content {
  background: rgba(255, 255, 255, 0.95);
  color: #333;
  border-radius: 18px 18px 18px 18px;
  padding: 8px 10px;
  max-width: 70%;
  position: relative;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

/* AI消息 */
.assistant-message,
.streaming-message {
  display: flex;
  justify-content: flex-start;
  gap: 12px;
  width: 100%;
}

.assistant-message .message-content,
.streaming-message .message-content {
  background: rgba(255, 255, 255, 0.95);
  color: #333;
  border-radius: 18px 18px 18px 18px;
  padding: 8px 10px;
  max-width: 70%;
  position: relative;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  border: 1px solid rgba(0, 0, 0, 0.05);
  backdrop-filter: blur(10px);
}

/* 头像样式 */
.message-avatar {
  flex-shrink: 0;
}

.user-avatar {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
}

.ai-avatar {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  color: white;
  box-shadow: 0 2px 8px rgba(79, 172, 254, 0.3);
}

.ai-avatar.streaming {
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% {
    box-shadow: 0 2px 8px rgba(79, 172, 254, 0.3);
  }
  50% {
    box-shadow: 0 2px 8px rgba(79, 172, 254, 0.6);
  }
  100% {
    box-shadow: 0 2px 8px rgba(79, 172, 254, 0.3);
  }
}

/* 消息文本 */
.message-text {
  line-height: 1.6;
  font-size: 15px;
  word-break: break-word;
  white-space: pre-wrap;
}

/* 打字动画 */
.typing-animation {
  position: relative;
}

.typing-cursor {
  display: inline-block;
  animation: blink 1s infinite;
  color: #4facfe;
  font-weight: bold;
}

@keyframes blink {
  0%,
  50% {
    opacity: 1;
  }
  51%,
  100% {
    opacity: 0;
  }
}

/* 推荐追问 */
.follow-up-container {
  margin: 20px 0;
  padding: 20px;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 16px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.follow-up-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
  font-weight: 600;
  color: #333;
  font-size: 14px;
}

.follow-up-questions {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.follow-up-btn {
  background: rgba(102, 126, 234, 0.1);
  color: #667eea;
  border: 1px solid rgba(102, 126, 234, 0.2);
  border-radius: 20px;
  padding: 8px 16px;
  font-size: 13px;
  transition: all 0.3s ease;
  cursor: pointer;
}

.follow-up-btn:hover {
  background: rgba(102, 126, 234, 0.2);
  border-color: rgba(102, 126, 234, 0.4);
  transform: translateY(-1px);
}

/* 输入区域 */
.chat-input-container {
  padding: 20px 0;
  background: transparent;
  position: relative;
  transition: all 0.3s ease;
}

.chat-input-container.drag-over {
  background: rgba(64, 158, 255, 0.1);
  border-radius: 20px;
}

/* 拖拽覆盖层 */
.drag-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(64, 158, 255, 0.2);
  border: 2px dashed #409eff;
  border-radius: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
}

.drag-content {
  text-align: center;
  color: #409eff;
}

.drag-content p {
  margin: 10px 0 0 0;
  font-weight: 600;
}

/* 附件预览区域 */
.attachments-preview {
  background: rgba(255, 255, 255, 0.9);
  border-radius: 15px;
  padding: 15px;
  margin-bottom: 10px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  backdrop-filter: blur(10px);
}

.attachments-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.attachments-title {
  font-size: 14px;
  font-weight: 600;
  color: #333;
}

.attachments-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.attachment-preview {
  position: relative;
  background: #f5f5f5;
  border-radius: 8px;
  padding: 8px;
  display: flex;
  align-items: center;
  gap: 8px;
  max-width: 200px;
}

.attachment-preview img {
  width: 40px;
  height: 40px;
  object-fit: cover;
  border-radius: 4px;
}

.file-preview-icon {
  color: #409eff;
  background: rgba(64, 158, 255, 0.1);
  padding: 4px;
  border-radius: 4px;
}

.attachment-info {
  flex: 1;
  overflow: hidden;
}

.attachment-name {
  display: block;
  font-size: 12px;
  font-weight: 500;
  color: #333;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.attachment-size {
  display: block;
  font-size: 10px;
  color: #999;
}

.remove-btn {
  position: absolute;
  top: -5px;
  right: -5px;
  background: #f56c6c;
  color: white;
  border: none;
  width: 20px;
  height: 20px;
  border-radius: 50%;
}

/* 上传进度 */
.upload-progress {
  background: rgba(255, 255, 255, 0.9);
  border-radius: 8px;
  padding: 10px 15px;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.progress-text {
  font-size: 12px;
  color: #666;
  white-space: nowrap;
}

/* 消息中的图片附件 */
.message-attachments {
  margin-bottom: 8px;
}

.attached-image {
  max-width: 200px;
  max-height: 200px;
  border-radius: 8px;
  cursor: pointer;
  transition: transform 0.2s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.attached-image:hover {
  transform: scale(1.02);
}

/* 消息中的文件附件 */
.attached-file {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  background: rgba(0, 0, 0, 0.05);
  border-radius: 8px;
  cursor: pointer;
  transition: background-color 0.2s ease;
  max-width: 250px;
}

.attached-file:hover {
  background: rgba(0, 0, 0, 0.1);
}

.attached-file .file-icon {
  color: #409eff;
  font-size: 20px;
}

.attached-file .file-name {
  font-weight: 500;
  color: #333;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex: 1;
}

.attached-file .file-size {
  font-size: 12px;
  color: #999;
}

/* 图片预览弹窗 */
.image-preview-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
  cursor: pointer;
}

.image-preview-container {
  position: relative;
  max-width: 90vw;
  max-height: 90vh;
  background: white;
  border-radius: 12px;
  overflow: hidden;
  cursor: default;
}

.preview-image {
  max-width: 100%;
  max-height: 70vh;
  display: block;
}

.preview-info {
  padding: 15px;
  background: white;
}

.preview-info h4 {
  margin: 0 0 5px 0;
  color: #333;
}

.preview-info p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.preview-close {
  position: absolute;
  top: 10px;
  right: 15px;
  background: rgba(0, 0, 0, 0.6);
  color: white;
  border: none;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  font-size: 18px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}

.input-wrapper {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 25px;
  padding: 4px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.chat-input {
  --el-input-border-color: transparent;
  --el-input-hover-border-color: transparent;
  --el-input-focus-border-color: transparent;
}

.chat-input .el-textarea__inner {
  border: none;
  background: transparent;
  padding: 16px 80px 16px 20px;
  font-size: 15px;
  line-height: 1.5;
  resize: none;
  border-radius: 21px;
  min-height: 24px;
  max-height: 120px;
}

.chat-input .el-textarea__inner:focus {
  box-shadow: none;
}

.input-actions {
  position: absolute;
  right: 8px;
  top: 50%;
  transform: translateY(-50%);
  display: flex;
  gap: 8px;
  align-items: center;
}

/* 上传按钮样式 */
.upload-btn {
  background: rgba(102, 126, 234, 0.1);
  border: 1px solid rgba(102, 126, 234, 0.2);
  color: #667eea;
  width: 32px;
  height: 32px;
  transition: all 0.3s ease;
}

.upload-btn:hover:not(:disabled) {
  background: rgba(102, 126, 234, 0.2);
  border-color: rgba(102, 126, 234, 0.4);
  transform: scale(1.05);
}

.upload-btn:disabled {
  background: #f5f5f5;
  border-color: #e0e0e0;
  color: #ccc;
  cursor: not-allowed;
  transform: none;
}

.send-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  width: 36px;
  height: 36px;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
  transition: all 0.3s ease;
}

.send-btn:hover:not(:disabled) {
  transform: scale(1.05);
  box-shadow: 0 6px 16px rgba(102, 126, 234, 0.4);
}

.send-btn:disabled {
  background: #ddd;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .brand-title {
    font-size: 2.5rem;
  }

  .chat-container {
    padding: 0 15px;
  }

  .user-message .message-content,
  .assistant-message .message-content,
  .streaming-message .message-content {
    max-width: 85%;
    padding: 12px 16px;
  }

  .welcome-card {
    padding: 30px 20px;
    margin: 0 20px;
  }

  .follow-up-container {
    margin: 15px 0;
    padding: 15px;
  }
}

/* KaTeX 样式适配 */
.katex {
  font-size: 1.1em !important;
  vertical-align: middle;
}

.katex-block {
  display: block;
  text-align: center;
  margin: 1em 0;
  overflow-x: auto;
  padding: 5px 0;
}

.user-message .katex,
.user-message .katex-block {
  color: white !important;
}

.katex-error {
  color: #f56c6c;
  font-style: italic;
}

/* 加载状态 */
.chat-input:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}
</style>
